package com.adopapa.nezhacloud.authc.service;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.adopapa.nezhacloud.authc.domain.RoleInfo;
import com.adopapa.nezhacloud.authc.domain.RoleInfoRepository;
import com.adopapa.nezhacloud.common.Tools;
import com.adopapa.nezhacloud.ddd.service.BaseDomainService;

import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;


@Service
public class RoleInfoService extends BaseDomainService<RoleInfo> {

	@Autowired
	private RoleInfoRepository roleInfoRepository;

	public RoleInfo getRoleInfoById(String id) {
		Optional<RoleInfo> optional = roleInfoRepository.findById(id);
		return optional.isPresent() ? optional.get() : null;
	}
	

	public Page<RoleInfo> getRoleInfoPage(int pageNo, int pageSize, RoleInfo roleInfo) {
		PageRequest pageRequest = buildPageRequest(pageNo, pageSize, Order.desc("id"));
		Specification<RoleInfo> specification = buildSpecification(roleInfo);
		Page<RoleInfo> page = roleInfoRepository.findAll(specification, pageRequest);
		return page;
	}

	public RoleInfo saveRoleInfo(RoleInfo roleInfo) {
		return roleInfoRepository.saveAndFlush(roleInfo);
	}

	public List<RoleInfo> saveRoleInfos(List<RoleInfo> roleInfos) {
		return roleInfoRepository.saveAllAndFlush(roleInfos);
	}

	public void deleteRoleInfo(String id) {
		roleInfoRepository.deleteById(id);
	}

	public void deleteRoleInfo(RoleInfo roleInfo) {
		roleInfoRepository.delete(roleInfo);
	}

	public void deleteRoleInfos(String... ids) {
		roleInfoRepository.deleteAllByIdInBatch(Arrays.asList(ids));
	}

	public void deleteRoleInfos(List<RoleInfo> roleInfos) {
		roleInfoRepository.deleteAllInBatch(roleInfos);
	}

	@SuppressWarnings("serial")
	@Override
	public Specification<RoleInfo> buildSpecification(RoleInfo roleInfo) {
		return new Specification<RoleInfo>() {
			@Override
			public Predicate toPredicate(Root<RoleInfo> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicates = new LinkedList<>();
				if (!Tools.empty(roleInfo.getRoleName())) {
					predicates.add(cb.like(root.get("roleName"), //
						"%".concat(roleInfo.getRoleName()).concat("%")));
				}
				return cb.and(predicates.toArray(new Predicate[0]));
			}

		};
	}
	
	// predicates.add(cb.equal(cb.substring(root.get("datagram"), 1, 23), dataPrefix));

}
